import {computed, ref} from 'vue';
import { message } from 'ant-design-vue';
import api from "@/utils/api";
import type {FailMode} from "./type.ts";

export const fetching = ref(false);
export const fmList = ref<FailMode[]>([]);
export const fmSearchList = ref<FailMode[]>([]);
export const newFmName = ref();
// 定义响应式变量
export const failModes = ref<FailMode[]>([{
    id: undefined,
    modeDesc: '',
    ctrlPlans: [{
        id: undefined,
        spec: '',
        capacityId: 2,
        capacityCn: '一次',
        frequencyValues: [],
        reactionPlanValues: [],
        frequencies: [],
        reactionPlans: [],
    }],
    isExpanded: false,
}]);

export const fmFocusIndex = computed(() => {
    return computeFmFocusIndex(failModes.value);
});

export const fmFocus = computed(() => {
    return computeFmFocus(failModes.value);
});
// 计算焦点索引
export const computeFmFocusIndex = (failModes: FailMode[]) => {
    for (let i = 0; i < failModes.length; i++) {
        const item = failModes[i];
        if (item?.isExpanded) {
            return i;
        }
    }
    return -1;
};

// 计算焦点失效模式
export const computeFmFocus = (failModes: FailMode[]) => {
    for (let i = 0; i < failModes.length; i++) {
        const item = failModes[i];
        if (item?.isExpanded) {
            return item;
        }
    }
    return undefined;
};

export const initializeFailModeFromRecord = (record:any) => {
    if (record && record.dtoFailMode4requirementList) {
        failModes.value = record.dtoFailMode4requirementList.map((fm: any) => ({
            fmId: fm.fmId,
            modeDesc: fm.fmDesc,
            ctrlPlans: fm.ctrlPlans?.map((cp: any) => ({
                cpId: cp.cpId,
                spec: cp.cpSpec,
                capacityId: cp.capacityId,
                capacityCn: cp.capacityCn,
                frequencies: cp.frequencyList.map((fq: any) => ({
                    id:fq.id,
                    cnDesc:fq.cnDesc,
                })) || [{
                    id:undefined,
                    cnDesc:'',
                }],
                reactionPlans: cp.reactionPlanList.map((rp: any) => ({
                    id:rp.id,
                    cnDesc:rp.cnDesc,
                })) || [{
                    id:undefined,
                    cnDesc:'',
                }],
                frequencyValues: [],
                reactionPlanValues: [],
            })) || [{
                cpId: undefined,
                spec: '',
                capacityId: 2,
                capacityCn: '一次',
                frequencies: [],
                reactionPlans: [],
            }],
            isExpanded: false,
        }));
        failModes.value.forEach(failMode => {
            failMode.ctrlPlans.forEach(ctrlPlan => {
                ctrlPlan.frequencies.forEach(fq =>{
                    ctrlPlan.frequencyValues?.push(fq.cnDesc);
                });
                ctrlPlan.reactionPlans.forEach(rp =>{
                    ctrlPlan.reactionPlanValues?.push(rp.cnDesc);
                });
            });
        });
        if(failModes.value[0]){
            failModes.value[0].isExpanded=true;
        }
    } else {
        resetFailModeData();
    }
}

export const createNewFailMode = async (roleCaseId: number, modeDesc: string,requirementId:any) => {
    try {
        fetching.value = true;

        await api.post('/failMode', {
            roleCaseId: roleCaseId,
            modeDesc: modeDesc,
        });
        const response = await api.get('/failMode', {
            params: {
                roleCaseId: roleCaseId,
                modeDesc: modeDesc,
            }
        });
        if(response.data[0].id){
            await api.post('/failMode/bindRequirement', {
                requirementId: requirementId,
                failModeId: response.data[0].id,
            });
        }


        message.success(`新痛点【${modeDesc}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建痛点失败');
        console.error('创建痛点失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};

// fm搜索方法
export const onFmSearch = async (modeDesc: string, roleCaseId?: number) => {
    if(fmList.value===undefined && roleCaseId){
        await fetchFailModes(roleCaseId);
    }
    if(fmList.value){
        fmSearchList.value = fmList.value
            .filter(fm => fm.modeDesc.includes(modeDesc))
            .sort((a, b) => a.id - b.id);
    }
    if(modeDesc.length>0){
        newFmName.value = modeDesc;
    }
};

// 获取fm列表
export const fetchFailModes = async (roleCaseId: number) => {
    try {
        fetching.value = true;

        const response = await api.get('/failMode', {
            params: {
                roleCaseId: roleCaseId,
            }
        });

        fmList.value = response.data;
    } catch (error) {
        message.error('获取痛点列表失败');
        console.error('获取痛点列表失败:', error);
    } finally {
        fetching.value = false;
    }
};

// 痛点选择变化
export const onFmChange = (value: any,failMode:FailMode) => {
    const fm= fmList.value.find(fm =>
        fm.modeDesc === value
    );

    if (fm) {
        failMode.id=fm.id;
        failMode.modeDesc=fm.modeDesc;
        newFmName.value=undefined;
    }

};

export const isFmNew = computed(() => {
    return (newFmName && newFmName.value!==undefined)
})

// 痛点失焦事件
export const onFmBlur = (failMode:FailMode) => {
    if (isFmNew.value) {
        failMode.id=undefined;
        failMode.modeDesc=newFmName.value;
        newFmName.value=undefined;
    }
};

// 添加失效模式
export const addFailMode = (failModes: FailMode[]) => {
    const lastFailMode = failModes[failModes.length - 1];
    if (lastFailMode && lastFailMode.modeDesc?.trim() !== '') {
        failModes.push({
            id: undefined,
            modeDesc: '',
            ctrlPlans: [{
                id: undefined,
                spec: '',
                capacityId: 2,
                capacityCn: '一次',
                frequencies: [],
                reactionPlans: [],
            }],
            isExpanded: false,
        });
    } else {
        message.warning('请先填写当前痛点描述');
    }
};

// 展开失效模式
export const expandFailMode = (failModes: FailMode[], index: number) => {
    failModes.forEach((fm, i) => {
        fm.isExpanded = i === index;
    });
};

// 移除失效模式
export const removeFailMode = (failModes: FailMode[], index: number) => {
    if (failModes.length > 1) {
        failModes.splice(index, 1);
    } else {
        message.warning('至少需要保留一个痛点');
    }
};

// 保存失效模式和控制计划
export const saveFailModesAndCtrlPlans = async (
    requirementId: number,
    failModes: FailMode[],
    selectedBusinessDto: any
) => {
    for (const [_failModeIndex, failMode] of failModes.entries()) {
        if (failMode.modeDesc.trim()) {
            // 保存失效模式
            const failModeData = {
                roleCaseId: selectedBusinessDto.id,
                modeDesc: failMode.modeDesc
            };

            const failModeResponse = await api.post('/failMode', failModeData);
            const failModeId = failModeResponse.data[0].id;

            // 关联失效模式和需求申请单
            const requirementFMData = {
                requirementId: requirementId,
                failModeId: failModeId
            };
            await api.post('/failMode/bindRequirement', requirementFMData);

            // 保存控制计划并关联
            for (const [_ctrlIndex, ctrlPlan] of failMode.ctrlPlans.entries()) {
                if (ctrlPlan.spec.trim()) {
                    const ctrlPlanData = {
                        failModeId: failModeId,
                        spec: ctrlPlan.spec,
                        capacityId: ctrlPlan.capacityId
                    };

                    const ctrlPlanResponse = await api.post('/ctrlPlan', ctrlPlanData);
                    const ctrlPlanId = ctrlPlanResponse.data[0].id;

                    // 关联控制计划和需求申请单
                    const requirementCPData = {
                        requirementId: requirementId,
                        ctrlPlanId: ctrlPlanId
                    };
                    await api.post('/ctrlPlan/bindRequirement', requirementCPData);
                }
            }
        }
    }
};

// 重置失效模式数据
export const resetFailModeData = () => {
    failModes.value = [{
        id: undefined,
        modeDesc: '',
        ctrlPlans: [{
            id: undefined,
            spec: '',
            capacityId: 2,
            capacityCn: '一次',
            frequencies: [],
            reactionPlans: [],
        }],
        isExpanded: true,
    }];
};

// 导出所有方法
export default {
    fetching,
    failModes,
    fmSearchList,
    fmFocusIndex,
    fmFocus,
    computeFmFocusIndex,
    computeFmFocus,
    onFmSearch,
    onFmChange,
    onFmBlur,
    addFailMode,
    createNewFailMode,
    fetchFailModes,
    expandFailMode,
    removeFailMode,
    saveFailModesAndCtrlPlans,
    initializeFailModeFromRecord,
    resetFailModeData
};